package cn.zl.common.manage.dashboard;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import oshi.SystemInfo;

import java.util.PriorityQueue;

public class CPUDashboard extends BaseDashboard {

    /**
     * 进程数
     */
    private int processorNum;

    private final PriorityQueue<CPURate> rateList = new PriorityQueue<>(NUM);

    public CPUDashboard(SystemInfo si) {
        super(si);
    }

    public void addRate(String time, int rate) {
        if(rateList.size()>= NUM ){
            rateList.poll();
        }
        CPURate cpuRate = new CPURate();
        cpuRate.time = time;
        cpuRate.rate = rate;
        rateList.add(cpuRate);
    }

    @Override
    public JSONObject encode() {
        JSONObject json = new JSONObject();
        json.put("processor_num", processorNum);
        final JSONArray rateList = new JSONArray();
        this.rateList.forEach(rate -> rateList.add(rate.encode()));
        json.put("rate_list", rateList);
        return json;
    }

    public static class CPURate implements BaseDashboard.IRate, Comparable<CPURate> {
        public String time;
        public int rate;

        @Override
        public JSONObject encode() {
            JSONObject json = new JSONObject();
            json.put("time", time);
            json.put("rate", rate);
            return json;
        }

        @Override
        public int compareTo(CPURate o) {
            return this.time.compareTo(o.time);
        }
    }

    public int getProcessorNum() {
        return processorNum;
    }

    public void setProcessorNum(int processorNum) {
        this.processorNum = processorNum;
    }

}
